package com.link2room.rodimus.facade.impl;

import com.link2room.aeriabots.dto.result.base.WxMemberInfoResDto;
import com.link2room.common.constant.DefaultValue;
import com.link2room.common.dto.result.base.MemberSessionDto;
import com.link2room.common.dto.threadlocal.ApiThreadLocal;
import com.link2room.common.exception.SysException;
import com.link2room.common.jpa.condition.ConditionDetail;
import com.link2room.common.jpa.condition.L2RCondition;
import com.link2room.common.jpa.criteria.CriteriaUtil;
import com.link2room.common.jpa.result.QueryResult;
import com.link2room.common.mns.MNSUtil;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.*;
import com.link2room.rodimus.constant.*;
import com.link2room.rodimus.dto.param.api.*;
import com.link2room.rodimus.dto.result.base.*;
import com.link2room.rodimus.entity.*;
import com.link2room.rodimus.facade.IGroupBuyingFacadeService;
import com.link2room.rodimus.feign.aeriabots.WxMemberInfoFeignService;
import com.link2room.rodimus.feign.rodimus.ExpressFeignService;
import com.link2room.rodimus.service.IGroupBuyingService;
import com.link2room.rodimus.service.IMallOrderService;
import com.link2room.rodimus.util.InvoiceUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.link2room.enums.exception.RodimusSysExceptionEnum.CREATE_GROUP_BUYING_TEAM_ERROR;
import static com.link2room.enums.exception.RodimusSysExceptionEnum.GROUP_BUYING_LIST_EROOR;
import static com.link2room.enums.exception.RodimusSysExceptionEnum.JOIN_THE_TEAM_ERROR;
import static com.link2room.rodimus.constant.GroupBuyingConstant.TEAM_DETAIL_STA.WAITING_PAY;
import static com.link2room.rodimus.constant.GroupBuyingConstant.TEAM_STA.WAITING_CAPTAIN_PAY;
import static com.link2room.rodimus.constant.MallOrderConstant.ORDER_TYPE.GROUP_BUYING;

/**
 * Created by LN on 2017/12/5
 */
@Component("groupBuyingFacadeService")
public class GroupBuyingFacadeServiceImpl implements IGroupBuyingFacadeService {

    @Resource
    private ICommonService commonService;
    @Resource
    private IMallOrderService mallOrderService;
    @Autowired
    private ExpressFeignService expressFeignService;
    @Autowired
    private WxMemberInfoFeignService wxMemberInfoFeignService;
    @Resource
    private IGroupBuyingService groupBuyingService;
    @Resource
    private MNSUtil mnsUtil;

    @Override
    public QueryResult<GroupBuyingBaseDto> groupBuyingBaseList(GroupBuyingListParamDto paramDto) throws Exception {
        String sortBy = paramDto.getSortBy();
        if (StringUtil.isNotBlank(sortBy)) {
            EnumSet<GroupBuyingBaseEntity.GroupBuyingBaseEntity_> enumSet = EnumSet.allOf(GroupBuyingBaseEntity.GroupBuyingBaseEntity_.class);
            String finalSortBy = sortBy;
            Optional<GroupBuyingBaseEntity.GroupBuyingBaseEntity_> e = enumSet.stream()
                    .filter(d -> d.toString().equals(finalSortBy))
                    .findAny();
            L2RAssert.isTrue(!e.isPresent(), new SysException(GROUP_BUYING_LIST_EROOR, "排序字段不存在"));
        } else {
            sortBy = GroupBuyingBaseEntity.BaseEntity_.listOrder.toString();
        }
        String order = paramDto.getOrder();
        if (StringUtil.isNotBlank(order)) {
            L2RAssert.isTrue(!CriteriaUtil.DESC.equals(order) && !CriteriaUtil.ASC.equals(order), new SysException(GROUP_BUYING_LIST_EROOR, "[order] is required for ASC or DESC"));
        } else {
            order = CriteriaUtil.ASC;
        }

        HashMap<String, String> orderBy = new HashMap<>();
        orderBy.put(sortBy, order);
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        L2RAssert.stringBlank(lhotelGroupCode, "[lhotelGruopCode] is null.");
        GroupBuyingBaseEntity find = new GroupBuyingBaseEntity();
        find.setLhotelGroupCode(lhotelGroupCode);
        find.setIsHalt(paramDto.getIsHalt());
        find.setCode(paramDto.getGroupBuyingCode());
        QueryResult<GroupBuyingBaseEntity> qres = commonService.findAllEQ(GroupBuyingBaseEntity.class, find, paramDto.getCurrentPage(), paramDto.getPageSize(), orderBy, null);
        QueryResult<GroupBuyingBaseDto> resDtos = ClassConverUtil.copyQueryResultToDtoQueryResult(qres, GroupBuyingBaseDto.class, true);
        if (CollectionUtils.isNotEmpty(resDtos.getResultlist())) {
            List<String> goodCodes = resDtos.getResultlist()
                    .stream()
                    .map(GroupBuyingBaseDto::getGoodCode)
                    .collect(Collectors.toList());
            L2RCondition goodCondition = new L2RCondition();
            goodCondition.setAndConditions(
                    new ConditionDetail[]{
                            new ConditionDetail(MallGoodBase.MallGoodBase_.goodCode.toString(), CriteriaUtil.Operator.IN, goodCodes),
                    }
            );
            QueryResult<MallGoodBase> goods = commonService.findAllByCondition(MallGoodBase.class, goodCondition);
            if (CollectionUtils.isNotEmpty(goods.getResultlist())) {
                QueryResult<MallGoodBaseDto> goodDtos = ClassConverUtil.copyQueryResultToDtoQueryResult(goods, MallGoodBaseDto.class, true);
                Map<String, List<MallGoodBaseDto>> map = goodDtos.getResultlist().stream().collect(Collectors.groupingBy(MallGoodBaseDto::getGoodCode));
                resDtos.getResultlist().forEach(dto -> {
                    if (CollectionUtils.isNotEmpty(map.get(dto.getGoodCode()))) {
                        dto.setMallGood(map.get(dto.getGoodCode()).get(0));
                    }
                });
            }
        }


        return resDtos;
    }

    @Override
    public GroupBuyingBaseDto groupBuyingBase(GroupBuyingListParamDto paramDto) throws Exception {
        String groupBuyingCode = paramDto.getGroupBuyingCode();
        L2RAssert.stringBlank(groupBuyingCode, "[groupBuyingCode] is null.");
        GroupBuyingBaseEntity find = new GroupBuyingBaseEntity();
        find.setCode(groupBuyingCode);
        GroupBuyingBaseEntity qres = commonService.findOneEQ(GroupBuyingBaseEntity.class, find);
        if (null != qres) {
            GroupBuyingBaseDto resDto = ClassConverUtil.copyProperties(qres, GroupBuyingBaseDto.class);
            MallGoodBase findGood = new MallGoodBase();
            findGood.setGoodCode(resDto.getGoodCode());
            MallGoodBase mallGoodEntity = commonService.findOneEQ(MallGoodBase.class, findGood);
            if (null != mallGoodEntity) {
                MallGoodBaseDto mallGood = ClassConverUtil.copyProperties(mallGoodEntity, MallGoodBaseDto.class);
                resDto.setMallGood(mallGood);
            }
            return resDto;
        } else {
            return null;
        }
    }

    @Override
    public GroupBuyingTeamCreatedResDto createGroupBuyingTeam(GroupBuyingTeamCreateParamDto paramDto) throws Exception {
        String groupBuyingCode = paramDto.getGroupBuyingCode();
        L2RAssert.stringBlank(groupBuyingCode, "[groupBuyingCode] is null.");
        GroupBuyingBaseEntity baseEntity = findGroupBuyingByCode(groupBuyingCode);
        L2RAssert.isTrue(null == baseEntity, new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "该团购活动不存在.[groupBuyingCode] is " + groupBuyingCode));
        Date nowDate = new Date();
        Date start = baseEntity.getStartDatetime();
        Date end = baseEntity.getEndDatetime();
        L2RAssert.isTrue(nowDate.after(end) || nowDate.before(start), new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "该团购不在活动时间范围内."));
        String isHalt = baseEntity.getIsHalt();
        L2RAssert.isTrue(isHalt.equals(DefaultValue.T), new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "该团购活动已停用."));

        MemberSessionDto session = ApiThreadLocal.getMemberSessionThreadLocal();
        //订单基础信息
        MallOrderBase mallOrderEntity = generateMallOrderBase(GROUP_BUYING, groupBuyingCode, baseEntity.getGoodCode(), baseEntity.getCaptainPrice(), paramDto);
        mallOrderEntity.setCancelDate(DateUtil.addHours(nowDate, baseEntity.getDuration()));
        //团队基础
        GroupBuyingTeamEntity groupBuyingTeamEntity = new GroupBuyingTeamEntity();
        WxMemberInfoResDto wxMemberInfo = wxMemberInfoFeignService.getMemberInfos(paramDto.getLhotelGroupCode(), session.getOpenid()).getResultInfo();
        if (null != wxMemberInfo) {
            groupBuyingTeamEntity.setCaptainHeadUrl(wxMemberInfo.getHeadimgurl());
            groupBuyingTeamEntity.setCaptainNickName(wxMemberInfo.getNickname());
            groupBuyingTeamEntity.setCaptainOpenid(wxMemberInfo.getOpenid());
        }
        groupBuyingTeamEntity.setMemberNo(session.getMemberNo());
        groupBuyingTeamEntity.setTeamCode(groupBuyingService.generateTeamNo());
        groupBuyingTeamEntity.setStartDatetime(nowDate);
        groupBuyingTeamEntity.setEndDatetime(DateUtil.addHours(nowDate, baseEntity.getDuration()));
        groupBuyingTeamEntity.setNumMember(baseEntity.getNumMember());
        groupBuyingTeamEntity.setSta(WAITING_CAPTAIN_PAY);
        groupBuyingTeamEntity.setGroupBuyingCode(groupBuyingCode);
        groupBuyingTeamEntity.setLhotelGroupCode(paramDto.getLhotelGroupCode());
        groupBuyingTeamEntity.setGroupBuyingName(baseEntity.getName());
        groupBuyingTeamEntity.setRemark(paramDto.getRemark());
        //生成队长信息
        GroupBuyingTeamDetailEntity newDetail = generateTeamDetail(mallOrderEntity.getOrderCode(), wxMemberInfo, groupBuyingTeamEntity, DefaultValue.T,paramDto.getRemark());

        try {
            groupBuyingService.saveTeam(mallOrderEntity, groupBuyingTeamEntity, newDetail);
        } catch (Exception e) {
            groupBuyingTeamEntity.setCaptainNickName(paramDto.getExpressMan());
            newDetail.setNickName(paramDto.getExpressMan());
            groupBuyingService.saveTeam(mallOrderEntity, groupBuyingTeamEntity, newDetail);
        }

        publishMsgForAutoCancel(mallOrderEntity.getOrderCode());


        GroupBuyingTeamCreatedResDto groupBuyingTeamCreatedResDto = new GroupBuyingTeamCreatedResDto();
        groupBuyingTeamCreatedResDto.setGroupBuyTeamCode(groupBuyingTeamEntity.getTeamCode());
        groupBuyingTeamCreatedResDto.setMallOrderNo(mallOrderEntity.getOrderCode());
        return groupBuyingTeamCreatedResDto;
    }

    @Override
    public GroupBuyingTeamCreatedResDto joinTheTeam(GroupBuyingJoinTheTeamParamDto paramDto) throws Exception {
        MemberSessionDto session = ApiThreadLocal.getMemberSessionThreadLocal();
        String teamCode = paramDto.getTeamCode();
        L2RAssert.stringBlank(teamCode, "[groupBuyingCode] is null.");
        GroupBuyingTeamEntity groupBuyingTeam = findTeamByCode(teamCode);
        L2RAssert.isTrue(null == groupBuyingTeam, new SysException(JOIN_THE_TEAM_ERROR, "团队不存在.[teamCode] is " + teamCode));
        String teamSta = groupBuyingTeam.getSta();
        L2RAssert.isTrue(!GroupBuyingConstant.TEAM_STA.PENDING.equals(teamSta), new SysException(JOIN_THE_TEAM_ERROR, "团队已经无效."));
        Date now = new Date();
        Date teamEndDate = groupBuyingTeam.getEndDatetime();
        L2RAssert.isTrue(now.after(teamEndDate), new SysException(JOIN_THE_TEAM_ERROR, "已经关团."));
        GroupBuyingTeamDetailEntity detailFind = new GroupBuyingTeamDetailEntity();
        detailFind.setTeamCode(teamCode);
        detailFind.setOpenid(session.getOpenid());
        GroupBuyingTeamDetailEntity detailEntity = commonService.findOneEQ(GroupBuyingTeamDetailEntity.class, detailFind);
        if (null != detailEntity) {
            String sta = detailEntity.getSta();
            L2RAssert.isTrue(GroupBuyingConstant.TEAM_DETAIL_STA.WAITING_PAY.equals(sta), new SysException(JOIN_THE_TEAM_ERROR, "已经参团，请支付."));
            L2RAssert.isTrue(GroupBuyingConstant.TEAM_DETAIL_STA.PAID.equals(sta), new SysException(JOIN_THE_TEAM_ERROR, "已经参团,请不要重复加团."));
        }
        long count = countTeamDetail(teamCode, GroupBuyingConstant.TEAM_DETAIL_STA.PAID);
        L2RAssert.isTrue(count >= groupBuyingTeam.getNumMember(), new SysException(JOIN_THE_TEAM_ERROR, "团队成员已经满员."));
        String groupBuyingCode = groupBuyingTeam.getGroupBuyingCode();
        GroupBuyingBaseEntity baseEntity = findGroupBuyingByCode(groupBuyingCode);
        L2RAssert.isTrue(null == baseEntity, new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "该团购活动不存在.[groupBuyingCode] is " + groupBuyingCode));
        Date nowDate = new Date();
        Date start = baseEntity.getStartDatetime();
        Date end = baseEntity.getEndDatetime();
        L2RAssert.isTrue(nowDate.after(end) || nowDate.before(start), new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "该团购不在活动时间范围内."));
        String isHalt = baseEntity.getIsHalt();
        L2RAssert.isTrue(isHalt.equals(DefaultValue.T), new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "该团购活动已停用."));

        MallOrderBase mallOrderEntity = generateMallOrderBase(GROUP_BUYING, groupBuyingTeam.getGroupBuyingCode(), baseEntity.getGoodCode(), baseEntity.getCaptainPrice(), paramDto);
        WxMemberInfoResDto wxMemberInfo = wxMemberInfoFeignService.getMemberInfos(paramDto.getLhotelGroupCode(), session.getOpenid()).getResultInfo();
        GroupBuyingTeamDetailEntity newDetail = generateTeamDetail(mallOrderEntity.getOrderCode(), wxMemberInfo, groupBuyingTeam, DefaultValue.F,paramDto.getRemark());
        try {
            groupBuyingService.joinTeam(mallOrderEntity, newDetail);
        } catch (Exception e) {
            newDetail.setNickName(paramDto.getExpressMan());
            groupBuyingService.joinTeam(mallOrderEntity, newDetail);
        }
        publishMsgForAutoCancel(mallOrderEntity.getOrderCode());

        GroupBuyingTeamCreatedResDto groupBuyingTeamCreatedResDto = new GroupBuyingTeamCreatedResDto();
        groupBuyingTeamCreatedResDto.setGroupBuyTeamCode(newDetail.getTeamCode());
        groupBuyingTeamCreatedResDto.setMallOrderNo(mallOrderEntity.getOrderCode());
        return groupBuyingTeamCreatedResDto;
    }

    @Override
    public QueryResult<GroupBuyingTeamDto> groupBuyingTeamList(GroupBuyingTeamFindParamDto paramDto) throws Exception {
        String groupBuyingCode = paramDto.getGroupBuyingCode();
        String sta = paramDto.getSta();
        String catpatinNickName = paramDto.getCatpatinNickName();
        String catpatinOpenid = paramDto.getCatpatinOpenid();
        GroupBuyingTeamEntity find = new GroupBuyingTeamEntity();
        find.setGroupBuyingCode(groupBuyingCode);
        find.setSta(sta);
        find.setIsHalt(paramDto.getIsHalt());
        find.setCaptainNickName(catpatinNickName);
        find.setCaptainOpenid(catpatinOpenid);
        find.setTeamCode(paramDto.getTeamCode());
        QueryResult<GroupBuyingTeamEntity> qres = commonService.findAllEQ(GroupBuyingTeamEntity.class, find, paramDto.getCurrentPage(), paramDto.getPageSize(), null, null);
        QueryResult<GroupBuyingTeamDto> qreDtos = ClassConverUtil.copyQueryResultToDtoQueryResult(qres, GroupBuyingTeamDto.class, true);
        return qreDtos;
    }

    @Override
    public GroupBuyingTeamDto groupBuyingTeam(GroupBuyingTeamFindParamDto paramDto) throws Exception {
        String teamCode = paramDto.getTeamCode();
        L2RAssert.stringBlank(teamCode, "[teamCode] is null.");
        GroupBuyingTeamEntity findTeam = new GroupBuyingTeamEntity();
        findTeam.setTeamCode(teamCode);
        GroupBuyingTeamEntity teamEntity = commonService.findOneEQ(GroupBuyingTeamEntity.class, findTeam);
        if (teamEntity != null) {
            GroupBuyingTeamDto teamDto = ClassConverUtil.copyPropertiesToDto(teamEntity, GroupBuyingTeamDto.class,true);
            GroupBuyingTeamDetailEntity detailFind = new GroupBuyingTeamDetailEntity();
            detailFind.setTeamCode(teamCode);
            detailFind.setSta(GroupBuyingConstant.TEAM_DETAIL_STA.PAID);
            QueryResult<GroupBuyingTeamDetailEntity> qres = commonService.findAllEQ(GroupBuyingTeamDetailEntity.class, detailFind);
            if (CollectionUtils.isNotEmpty(qres.getResultlist())) {
                QueryResult<GroupBuyingTeamDetailDto> details = ClassConverUtil.copyQueryResultToDtoQueryResult(qres, GroupBuyingTeamDetailDto.class, true);
                teamDto.setGroupBuyingTeamDetails(details.getResultlist());
            }
            return teamDto;
        } else {
            return null;
        }


    }

    @Override
    public QueryResult<GroupBuyingTeamDto> currentUserTeams(GroupBuyingCurrentUserTeamFindParamDto paramDto) throws Exception {
        String groupBuyingCode = paramDto.getGroupBuyingCode();
        List<String> stas = paramDto.getStas();
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        String openid = ApiThreadLocal.getMemberSessionThreadLocal().getOpenid();
        L2RAssert.stringBlank(openid, "[openid] is required.");

        L2RCondition detailFindCondition = new L2RCondition();
        detailFindCondition.setAndConditions(
                new ConditionDetail[]{
                        new ConditionDetail(GroupBuyingTeamDetailEntity.GroupBuyingTeamDetailEntity_.sta.toString(), CriteriaUtil.Operator.NOTIN,Arrays.asList(WAITING_PAY, GroupBuyingConstant.TEAM_DETAIL_STA.AUTO_CANCEL)),
                        new ConditionDetail(GroupBuyingTeamDetailEntity.GroupBuyingTeamDetailEntity_.openid.toString(), CriteriaUtil.Operator.EQ,openid),
                        new ConditionDetail(GroupBuyingTeamDetailEntity.BaseEntity_.lhotelGroupCode.toString(), CriteriaUtil.Operator.EQ,paramDto.getLhotelGroupCode()),
                }
        );
        QueryResult<GroupBuyingTeamDetailEntity> detailQres = commonService.findAllByCondition(GroupBuyingTeamDetailEntity.class, detailFindCondition);

        QueryResult<GroupBuyingTeamDetailDto> details = ClassConverUtil.copyQueryResultToDtoQueryResult(detailQres, GroupBuyingTeamDetailDto.class, true);

        if (CollectionUtils.isNotEmpty(detailQres.getResultlist())) {
            Set<String> teamCodeSets = details.getResultlist()
                    .stream()
                    .map(GroupBuyingTeamDetailDto::getTeamCode)
                    .collect(Collectors.toSet());
            L2RCondition condition = new L2RCondition();
            condition.setAndConditions(
                    new ConditionDetail[]{
                            new ConditionDetail(GroupBuyingTeamEntity.GroupBuyingTeamEntity_.teamCode.toString(), CriteriaUtil.Operator.IN, teamCodeSets),
                            new ConditionDetail(GroupBuyingTeamEntity.BaseEntity_.lhotelGroupCode.toString(), CriteriaUtil.Operator.EQ, lhotelGroupCode),
                            new ConditionDetail(GroupBuyingTeamEntity.GroupBuyingTeamEntity_.sta.toString(), CriteriaUtil.Operator.IN, stas),
                            new ConditionDetail(GroupBuyingTeamEntity.GroupBuyingTeamEntity_.groupBuyingCode.toString(), CriteriaUtil.Operator.EQ, groupBuyingCode),
                    }
            );
            QueryResult<GroupBuyingTeamEntity> teamQres = commonService.findAllByCondition(GroupBuyingTeamEntity.class, condition,paramDto.getCurrentPage(),paramDto.getPageSize());
            if (CollectionUtils.isNotEmpty(teamQres.getResultlist())) {
                Map<String, List<GroupBuyingTeamDetailDto>> detailMap = details.getResultlist()
                        .stream().collect(Collectors.groupingBy(GroupBuyingTeamDetailDto::getTeamCode));
                QueryResult<GroupBuyingTeamDto> teams = ClassConverUtil.copyQueryResultToDtoQueryResult(teamQres, GroupBuyingTeamDto.class, true);
                teams.getResultlist().forEach(team -> {
                    List<GroupBuyingTeamDetailDto> detailList = detailMap.get(team.getTeamCode());
                    if (CollectionUtils.isNotEmpty(detailList)) {
                        team.setGroupBuyingTeamDetails(detailList);
                    }
                });
                return teams;
            }
        }
        QueryResult qr = new QueryResult();
        qr.setCurrentPage(0);
        qr.setTotalrecord(0);
        return qr;
    }

    @Override
    public GroupBuyingTeamCurrentUserDto currentUserTeam(GroupBuyingTeamFindParamDto paramDto) throws Exception {
        String teamCode = paramDto.getTeamCode();
        L2RAssert.stringBlank(teamCode, "[teamCode] is null.");
        GroupBuyingTeamEntity findTeam = new GroupBuyingTeamEntity();
        findTeam.setTeamCode(teamCode);
        GroupBuyingTeamEntity teamEntity = commonService.findOneEQ(GroupBuyingTeamEntity.class, findTeam);
        if (teamEntity != null) {
            GroupBuyingTeamCurrentUserDto teamDto = ClassConverUtil.copyPropertiesToDto(teamEntity, GroupBuyingTeamCurrentUserDto.class,true);
            //查找当前用户是否已经支付
            GroupBuyingTeamDetailEntity findGroupBuyingTeamDetailCurrent = new GroupBuyingTeamDetailEntity();
            findGroupBuyingTeamDetailCurrent.setOpenid(ApiThreadLocal.getMemberSessionThreadLocal().getOpenid());
            findGroupBuyingTeamDetailCurrent.setTeamCode(teamCode);
            findGroupBuyingTeamDetailCurrent.setLhotelGroupCode(paramDto.getLhotelGroupCode());
            GroupBuyingTeamDetailEntity groupBuyingTeamDetailCurrentUser = commonService.findOneEQ(GroupBuyingTeamDetailEntity.class, findGroupBuyingTeamDetailCurrent);


            if(null == groupBuyingTeamDetailCurrentUser ||
                    (!GroupBuyingConstant.TEAM_DETAIL_STA.PAID.equals(groupBuyingTeamDetailCurrentUser.getSta()) &&  !GroupBuyingConstant.TEAM_DETAIL_STA.WAITING_PAY.equals(groupBuyingTeamDetailCurrentUser.getSta()))){
                teamDto.setIsInTeam(DefaultValue.F);
                teamDto.setNeedPay(DefaultValue.F);
            }else if(WAITING_PAY.equals(groupBuyingTeamDetailCurrentUser.getSta())){
                teamDto.setIsInTeam(DefaultValue.T);
                teamDto.setOrderNo(groupBuyingTeamDetailCurrentUser.getOrderNo());
                teamDto.setNeedPay(DefaultValue.T);
            }else{
                teamDto.setIsInTeam(DefaultValue.T);
                teamDto.setNeedPay(DefaultValue.F);
            }

            L2RCondition detailFindCondition = new L2RCondition();
            detailFindCondition.setAndConditions(
                    new ConditionDetail[]{
                            new ConditionDetail(GroupBuyingTeamDetailEntity.GroupBuyingTeamDetailEntity_.sta.toString(), CriteriaUtil.Operator.IN, Arrays.asList(GroupBuyingConstant.TEAM_DETAIL_STA.PAID, GroupBuyingConstant.TEAM_DETAIL_STA.MANUAL_FINISH)),
                            new ConditionDetail(GroupBuyingTeamDetailEntity.GroupBuyingTeamDetailEntity_.teamCode.toString(), CriteriaUtil.Operator.EQ,teamCode),
                            new ConditionDetail(GroupBuyingTeamDetailEntity.BaseEntity_.lhotelGroupCode.toString(), CriteriaUtil.Operator.EQ,paramDto.getLhotelGroupCode()),
                    }
            );
            QueryResult<GroupBuyingTeamDetailEntity> qres = commonService.findAllByCondition(GroupBuyingTeamDetailEntity.class, detailFindCondition);
            if (CollectionUtils.isNotEmpty(qres.getResultlist())) {
                QueryResult<GroupBuyingTeamDetailDto> details = ClassConverUtil.copyQueryResultToDtoQueryResult(qres, GroupBuyingTeamDetailDto.class, true);
                teamDto.setGroupBuyingTeamDetails(details.getResultlist());
            }
            return teamDto;
        } else {
            return null;
        }
    }

    private void publishMsgForAutoCancel(String orderCode) {
        MallOrderCancelParamDto cancelParam = new MallOrderCancelParamDto();
        cancelParam.setOrderNo(orderCode);
        mnsUtil.putDelayMessageToQueue(RodimusMnsConstant.QUEUE_MALL_ORDER_CANCEL, JacksonUtil.beanToJson(cancelParam), 1800 + 300);
    }

    private GroupBuyingTeamDetailEntity generateTeamDetail(String orderNo, WxMemberInfoResDto wxMemberInfo, GroupBuyingTeamEntity groupBuyingTeamEntity, String isCaptain,String remark) throws Exception {
        MemberSessionDto session = ApiThreadLocal.getMemberSessionThreadLocal();
        GroupBuyingTeamDetailEntity newDetail = new GroupBuyingTeamDetailEntity();
        if (null != wxMemberInfo) {
            newDetail.setHeadUrl(wxMemberInfo.getHeadimgurl());
            newDetail.setNickName(wxMemberInfo.getNickname());
            newDetail.setOpenid(wxMemberInfo.getOpenid());
        }
        newDetail.setTeamCode(groupBuyingTeamEntity.getTeamCode());
        newDetail.setOrderNo(orderNo);
        newDetail.setSta(WAITING_PAY);
        newDetail.setMemberNo(session.getMemberNo());
        newDetail.setLhotelGroupCode(session.getLhotelGroupCode());
        newDetail.setIsCaptain(isCaptain);
        newDetail.setRemark(remark);
        return newDetail;
    }

    private long countTeamDetail(String teamCode, String sta) throws Exception {
        GroupBuyingTeamDetailEntity countCon = new GroupBuyingTeamDetailEntity();
        countCon.setTeamCode(teamCode);
        countCon.setSta(sta);
        return commonService.getCountAllEQ(GroupBuyingTeamDetailEntity.class, countCon, null);
    }

    private GroupBuyingTeamEntity findTeamByCode(String teamCode) throws Exception {
        GroupBuyingTeamEntity find = new GroupBuyingTeamEntity();
        find.setTeamCode(teamCode);
        return commonService.findOneEQ(GroupBuyingTeamEntity.class, find);
    }

    private MallOrderBase generateMallOrderBase(String orderType, String productCode, String goodCode, BigDecimal captainPrice, GroupBuyingTeamCreateParamDto paramDto) throws Exception {
        MemberSessionDto session = ApiThreadLocal.getMemberSessionThreadLocal();
        String openid = session.getOpenid();
        String memberNo = session.getMemberNo();
        MallGoodBase find = new MallGoodBase();
        find.setGoodCode(goodCode);
        MallGoodBase mallGood = commonService.findOneEQ(MallGoodBase.class, find);
        L2RAssert.isTrue(mallGood == null, new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "商品不存在.[goodCode] is " + goodCode));
        L2RAssert.isTrue(mallGood.getIsHalt().equals(DefaultValue.T), new SysException(CREATE_GROUP_BUYING_TEAM_ERROR, "商品已经下架."));
        String newOrderNo = mallOrderService.generateNewOrderNo();
        MallOrderBase mallOrderBase = new MallOrderBase();
        mallOrderBase.setSta(MallOrderConstant.Sta.needPay);
        mallOrderBase.setOrderCode(newOrderNo);
        mallOrderBase.setLhotelGroupCode(paramDto.getLhotelGroupCode());
        mallOrderBase.setOrderCode(newOrderNo);
        mallOrderBase.setMemberNo(memberNo);
        mallOrderBase.setOpenid(openid);
        mallOrderBase.setPoint(BigDecimal.ZERO);
        mallOrderBase.setPrice(captainPrice);
        mallOrderBase.setAmount(1);
        mallOrderBase.setGoodType(mallGood.getGoodType());
        mallOrderBase.setOrderType(orderType);
        mallOrderBase.setProductCode(productCode);
        mallOrderBase.setGoodContant(mallGood.getName());
        //快递信息
        if (MallGoodsConstant.GoodType.MG.equals(mallOrderBase.getGoodType())) {
            mallOrderBase.setNeedExpress(DefaultValue.T);
            mallOrderBase.setExpressSta(MallOrderConstant.EXPRESS_STA.INIT);
            mallOrderBase.setExpressRemark(paramDto.getExpressRemark());
            mallOrderBase.setExpressAddress(paramDto.getExpressAddress());
            mallOrderBase.setExpressMobile(paramDto.getExpressMobile());
            mallOrderBase.setExpressMan(paramDto.getExpressMan());

            /*//新建发货信息 //在支付成功后再创建发货信息
            ExpressNewInsideParamDto expressParamDto = new ExpressNewInsideParamDto();
            expressParamDto.setMemberNo(mallOrderBase.getMemberNo());
            expressParamDto.setMobile(paramDto.getExpressMobile());
            expressParamDto.setAddress(paramDto.getExpressAddress());
            expressParamDto.setGoodAmount(mallOrderBase.getAmount());
            expressParamDto.setGoodName(mallGood.getName());
            expressParamDto.setGoodCode(mallGood.getGoodCode());
            expressParamDto.setSourceNo(mallOrderBase.getOrderCode());
            expressParamDto.setReceiverName(paramDto.getExpressMan());
            expressParamDto.setSourceType(ExpressConstant.SOURCE_TYPE.GROUPBUYING);
            expressParamDto.setRemark("团购商城订单");
            expressParamDto.setLhotelGroupCode(paramDto.getLhotelGroupCode());
            expressParamDto.setOpenid(mallOrderBase.getOpenid());
            expressFeignService.newExpress(expressParamDto);*/

        } else {
            mallOrderBase.setNeedExpress(DefaultValue.F);
            mallOrderBase.setExpressSta(MallOrderConstant.EXPRESS_STA.NONE);
            mallOrderBase.setExpressRemark(paramDto.getExpressRemark());
        }


        //发票相关
        InvoiceDetailDto invoiceDetailDto = paramDto.getInvoiceDetailDto();
        String needInvoice = mallOrderBase.getNeedInvoice();
        if (StringUtil.isNotBlank(needInvoice) && DefaultValue.T.equals(needInvoice)) {
            InvoiceUtil.checkInvoice(invoiceDetailDto);
            mallOrderBase.setInvoiceTitle(invoiceDetailDto.getInvoiceTitle());
            mallOrderBase.setInvoiceRemark(
                    StringUtils.join(Stream.of(
                            invoiceDetailDto.getInvoiceTitleTypeDes(),
                            invoiceDetailDto.getInvoiceTypeDes(),
                            invoiceDetailDto.getPayerDes(),
                            invoiceDetailDto.getProviderDes(),
                            invoiceDetailDto.getEarlyPrepareDes(),
                            invoiceDetailDto.getPostTypeDes()
                            ).filter(StringUtil::isNotBlank).toArray()
                            , ",")
            );
        }
        return mallOrderBase;
    }

    private GroupBuyingBaseEntity findGroupBuyingByCode(String groupBuyingCode) throws Exception {
        GroupBuyingBaseEntity find = new GroupBuyingBaseEntity();
        find.setCode(groupBuyingCode);
        return commonService.findOneEQ(GroupBuyingBaseEntity.class, find);
    }

}
